<?php


namespace api\app\controller;


use api\app\model\UserModel;
use api\app\validate\UserValidate;
use cmf\controller\RestBaseController;
use think\Request;
use \think\facade\Filesystem;

class UserController extends RestBaseController
{
    //注册
    public function register()
    {
        $data = input('post.');
        $validate = new UserValidate();
        $res = $validate->scene('register')->check($data);
        if (!$res){
            $this->error($validate->getError());
        }
        $user = UserModel::where('mobile',$data['mobile'])->find();
        if ($user){
            $this-> error('该用户已被注册');
        }
        $c = checkCode($data['mobile'],$data['code']);
        if (!$c){
             $this->error('验证码错误');
        }
        $data['create_time'] = time();
        if (UserModel::create($data)){
            $this->success('注册成功');
        }


    }
    //登录
    public function login()
    {
        $data = input('post.');
        $validate = new UserValidate();
        $res = $validate->scene('login')->check($data);
        if (!$res){
            $this->error($validate->getError());
        }
        $user = UserModel::where('mobile',$data['mobile'])->find();
        if (!$user){
            $this-> error('该用户未注册');
        }
        $c = checkCode($data['mobile'],$data['code']);
        if (!$c){
            $this->error('验证码错误');
        }
        $token = createToken($user['mobile'],$user['id']);
         $this->success('登录成功',[
             'data' => $token
         ]);

    }
    //发送验证码
    public function SmsCode()
    {
        $mobile = input('post.mobile');
        return SendCode($mobile);
    }

    //查询用户数据
    public function userList()
    {
        $id = input('id/d');
        if (!$id) {
            $this->error('参数错误');
        }
        $data = UserModel::field('id,image,name,mobile')->find($id);
        if (!$data){
            $this->error('无用户');
        }
        $this->success('查询成功',[
            'data' => $data
        ]);

    }
    //修改功能
    public function edit()
    {
        $data = input('post.');
        //halt($data);
       if (!$data){
           $this->error('参数错误');
       }
        $validate = new UserValidate();
        $res = $validate->scene('edit')->check($data);
        if (!$res){
            $this->error($validate->getError());
        }
        if (!$data['id']){
            $this->error('ID错误');
        }
        $user = UserModel::find($data['id']);
        $user->image = $data['image'];
        $user->name = $data['name'];
        $user->mobile = $data['mobile'];
        $user->update_time = time();
        if ($user->save()){
            $this->success('保存成功');
        }else{
            $this->error('保存失败');
        }

    }


}